//
//  ViewController.m
//  Project6
//
//  Created by ToanDK on 11/13/12.
//  Copyright (c) 2012 DungNP. All rights reserved.
//

#import "ViewController.h"
#import "WelcomViewController.h"
#import "MBProgressHUD.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"




@implementation ViewController

-(void)viewWillAppear:(BOOL)animated
{
    // hide navigation bar
    self.navigationController.navigationBarHidden = YES;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    txtUserName.placeholder = @"Username";
    txtPassWorld.placeholder = @"Password";
    // get udid and device name
    uniqueIdentifier = [[UIDevice currentDevice] uniqueIdentifier];
    deviceName =[[UIDevice currentDevice] name];
    
    UIImage* buttonImage =[[UIImage imageNamed:@"greenButton"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
    UIImage* buttonImageON =[[UIImage imageNamed:@"greenButtonOn"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
    
    [btnLogin setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [btnLogin setBackgroundImage:buttonImageON forState:UIControlStateHighlighted];
    [btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnLogin setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"greyBackground"]];
    
    // Check user have logined
    NSUserDefaults * loginStatus = [NSUserDefaults standardUserDefaults];
    NSString * status =[loginStatus objectForKey:@"login"];
    NSLog(@"status:%@",status);
    if(status)
    {
        if( [status isEqual:@"YES"])
        {
            // Check API with webservice
            ISCHECK_LOGIN =TRUE;
            
            // show indicator
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText =@"Processing";
            
            NSString * kURLLoginCheck = [kBASE_URL stringByAppendingFormat:@"%@",@"account.php?api=%@&action=%@&user=%@&pass=%@&udid=%@&device=%@"];
            NSString * urlString = [NSString stringWithFormat:kURLLoginCheck,kAPI,kACTION_CHECK,[loginStatus objectForKey:@"user"],[loginStatus objectForKey:@"password"],uniqueIdentifier,deviceName];
            
            NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:
                                               NSUTF8StringEncoding]];
            NSLog(@"url:%@",url);
            
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
            
            [request setDelegate:self];
            [request startAsynchronous];
            
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

//login button click
-(IBAction) btnLogin_Click:(id)sender
{
    NSLog(@"login button click");

//    // Get device unique ID
//   
//    NSString *uniqueIdentifier = [[UIDevice currentDevice] uniqueIdentifier];
//    NSString * deviceName =[[UIDevice currentDevice] name];
    
    //uniqueIdentifier = @"76yh3ed6ytghb43ed98ik";
    // show indicator
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText =@"Processing";
    
     NSString * kURLLogin = [kBASE_URL stringByAppendingFormat:@"%@",@"account.php?api=%@&action=%@&user=%@&pass=%@&udid=%@&device=%@"];
    NSString * urlString = [NSString stringWithFormat:kURLLogin,kAPI,kACTION_LOGIN,txtUserName.text,txtPassWorld.text,uniqueIdentifier,deviceName];
    
    NSLog(@"url:%@",urlString);
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:
                 NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",urlString]];
    NSLog(@"url:%@",url);
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    [request setDelegate:self];
    [request startAsynchronous];
        
}

-(void)requestFinished:(ASIHTTPRequest *)request
{
    
    if (request.responseStatusCode == 400) {
        NSLog(@"Invalid code");
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Login" message:@"Invalid code" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];

    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Login" message:@"Code already used" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];

    } else if (request.responseStatusCode == 200) {
        NSString *responseString = [request responseString];
        NSLog(@"response string:%@",responseString);
        if (ISCHECK_LOGIN) {
            if([responseString isEqualToString:@"TRUE"])
            {
                // go to welcom screen
                WelcomViewController *welcomCtr = [[WelcomViewController alloc] initWithNibName:@"WelcomViewController" bundle:nil];
                // set peroperties to using for logout
                welcomCtr.username = txtUserName.text;
                welcomCtr.password = txtPassWorld.text;
                welcomCtr.udid = uniqueIdentifier;
                welcomCtr.devicename = deviceName;
                
                [self.navigationController pushViewController:welcomCtr animated:YES];
            }
            else
            {
                ISCHECK_LOGIN = NO;
            }
        }
        else // Login click
        {
        
            // DEVICE ALREADY REGISTERED, ERROR, WRONG PASSWORD
            if([responseString isEqualToString:@"FALSE"] || [responseString isEqualToString:@"ERROR"] || [responseString isEqualToString:@"WRONG PASSWORD"])
            {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Login" message:@"Login fail, please check your username and password" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];

            }
            else
            {
                // Save login status to userdefault
                NSUserDefaults * loginStatus = [NSUserDefaults standardUserDefaults];
                [loginStatus setObject:@"YES" forKey:@"login"];
                [loginStatus setObject:txtUserName.text forKey:@"user"];
                [loginStatus setObject:txtPassWorld.text forKey:@"password"];
               
                // go to welcom screen
                WelcomViewController *welcomCtr = [[WelcomViewController alloc] initWithNibName:@"WelcomViewController" bundle:nil];
                // set properties using for logout
                welcomCtr.username = txtUserName.text;
                welcomCtr.password = txtPassWorld.text;
                welcomCtr.udid = uniqueIdentifier;
                welcomCtr.devicename = deviceName;
                
                [self.navigationController pushViewController:welcomCtr animated:YES];
            }
        }
        
    } else {
        NSLog(@"Unexpected error");
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Login" message:@"Unexpected error" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"error:%@",error.localizedDescription);
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Login" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}


// AVOID KEYBOAR OVER UP THE TEXTFIELD

// implement textfile delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
        
    NSInteger nextTag = textField.tag + 1;
    // Try to find next responder
    UIResponder *nextResponder = [textField.superview viewWithTag:nextTag];
    
    if (nextResponder) {
        [bgScrollView setContentOffset:CGPointMake(0,textField.center.y-180) animated:YES];
        // Found next responder, so set it.
        [nextResponder becomeFirstResponder];
        
        
    } else {
        [bgScrollView setContentOffset:CGPointMake(0,0) animated:YES];
        [textField resignFirstResponder];
        [self btnLogin_Click:nil] ;
        return YES;
    }
    
   
    
    return NO;
}

// called when textField start editting.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(textField==txtPassWorld)
        textField.secureTextEntry = YES;
    if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
        [bgScrollView setContentOffset:CGPointMake(0,textField.center.y-180) animated:YES];
    
}



@end
